import { useEffect, useState } from 'react';
import { Form, Upload, Button, Icon, message, Modal } from 'antd';
import { axconst } from '@/shared/axconst';
import { AxValidator } from '../AxValidator';
import './index.css';

const FormItem = Form.Item;
const {
  inlineFormItemLayout,
  inlineFormItemLayoutAllRowTwo,
  inlineFormItemLayoutAllRowThree,
} = axconst;

const getFileType = t => {
  switch (t) {
    case 'xls':
      return 'application/vnd.ms-excel';
    case 'xlsx':
      return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    case 'txt':
      return 'text/plain';
    case 'jpg':
    case 'jpe':
    case 'jpeg':
      return 'image/jpeg';
    case 'png':
      return 'image/png';
    case 'gif':
      return 'image/gif';
    default:
      return '';
  }
};
/**
 * 自定义文本框
 * @param label 标签
 * @param field 字段名称
 * @param uploadUrl 上传路径（需配置，默认：null）
 * @param extraData 额外的数据（默认：{}）
 * @param fileType 文件格式（默认：xlsx）
 * @param required 是否必填
 * @param message 提示信息（如果添加了，所有错误提示为改信息）
 * @param validator 自定义验证函数
 * @param hidden 是否隐藏
 * @param fileList 已经上传的文件列表
 */
export function AxUpload(props) {
  let formItemLayout = {};
  const { fileList: fileListFromProps } = props;
  const [fileList, setFileList] = useState(fileListFromProps);
  const {
    formItemLayoutFromProps = null,
    uploadUrl = null,
    extraData = {},
    fileType = 'xlsx',
    ...rest
  } = props;
  if (!uploadUrl || uploadUrl == '') {
    message.error(`暂无上传路径！`);
  }

  useEffect(() => {
    setFileList(fileListFromProps || []);
  }, [fileListFromProps]);

  const handleBeforeUpload = file => {
    let isJpgOrPng = false;
    if (file.type != '') {
      isJpgOrPng = file.type === getFileType(fileType);
    } else {
      const name = file.name.split('.');
      const len = name.length;
      if (name && len > 0 && name[len - 1] && name[len - 1] === fileType) {
        isJpgOrPng = true;
      }
    }
    if (!isJpgOrPng) {
      message.error('你只能上传xlsx格式的文件');
    }
    return isJpgOrPng;
  };

  const handleDownload = file => {};

  const handleGetValueFromEvent = e => {
    if (e.file.status === 'done') {
      // const id = /"id":"\d*"/.exec(e.file.response);
      // if (id && id.length > 0) {
      //     const i = /\d+/.exec(id[0]);
      //     if (i && i.length > 0) {
      //         return i[0];
      //     }
      // }
      if (e.file.response.data && e.file.response.data.src) {
        return e.file.response.data.id;
      }
    }
    return null;
  };

  const handleChange = info => {
    if (info.file.status !== 'uploading') {
      // console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name}上传成功！`);
    } else if (info.file.status === 'error') {
      if (info.file.error.status === 401) {
        message.error(`暂无上传权限！`);
      } else {
        message.error(`${info.file.name}上传失败！`);
      }
    }

    /** 控制上传数量为1个 */
    let fileList = [...info.fileList];
    // 1. Limit the number of uploaded files
    // Only to show two recent uploaded files, and old ones will be replaced by the new
    fileList = fileList.slice(-1);
    // 2. Read from response and show file link
    fileList = fileList.map(file => {
      if (file.status === 'done') {
        // const reg = new RegExp('(http|https)://(\\S+?).' + file.name.split('.')[1] + '', 'g');
        // const path = reg.exec(file.response);
        // if (path && path.length > 0) {
        //     file.url = path[0];
        // }
        if (file.response.data && file.response.data.src) {
          file.url = file.response.data.src;
        }
      }
      return file;
    });
    /** 只展示有状态信息的文件，文件格式不正确时，没有状态信息，需要过滤掉 */
    fileList = fileList.filter(i => i.status);
    setFileList(fileList);
  };

  const uploadProps = {
    name: 'file',
    action: uploadUrl,
    headers: {
      authorization: localStorage.getItem('ax-auth-token'),
    },
    data: extraData,
    showUploadList: { showDownloadIcon: false },
    fileList: fileList,
    beforeUpload: handleBeforeUpload,
    onDownload: handleDownload,
    onChange: handleChange,
  };

  switch (props.wholerow) {
    case 'two':
      formItemLayout = { ...inlineFormItemLayoutAllRowTwo };
      break;
    case 'three':
      formItemLayout = { ...inlineFormItemLayoutAllRowThree };
      break;
    default:
      formItemLayout = formItemLayoutFromProps
        ? formItemLayoutFromProps
        : { ...inlineFormItemLayout };
      break;
  }

  return props.hidden ? null : (
    <FormItem {...formItemLayout} label={props.label}>
      {props.form.getFieldDecorator(props.field, {
        initialValue: props.value,
        // valuePropName: 'fileList123',
        getValueFromEvent: handleGetValueFromEvent,
        rules: [
          {
            label: props.label,
            required: props.required,
            message: props.message,
            validator: props.validator ? props.validator : AxValidator,
          },
        ],
      })(
        <Upload {...uploadProps}>
          <Button>
            <Icon type="upload" /> 选择文件
          </Button>
        </Upload>,
      )}
    </FormItem>
  );
}
/**
 * 自定义文本框
 * @param label 标签
 * @param field 字段名称
 * @param uploadUrl 上传路径（需配置，默认：null）
 * @param extraData 额外的数据（默认：{}）
 * @param uploadCount 上传数量（默认：1）
 * @param required 是否必填
 * @param message 提示信息（如果添加了，所有错误提示为改信息）
 * @param validator 自定义验证函数
 * @param hidden 是否隐藏
 */
export function AxUploadPicture(props) {
  let formItemLayout = {};
  const initFile = props.value || [];
  // [{
  //     uid: '-1',
  //     name: props.value || '图片',
  //     status: 'done',
  //     url: props.value,
  // }] : [];
  const [fileList, setFileList] = useState(initFile);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const {
    formItemLayoutFromProps = null,
    uploadUrl = null,
    extraData = {},
    uploadCount = 1,
    ...rest
  } = props;
  if (!uploadUrl || uploadUrl == '') {
    message.error(`暂无上传路径！`);
  }
  const getBase64 = file => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  };
  const handleCancel = () => setPreviewVisible(false);

  /** 检查是否是图片格式 */
  const handleCheckIsPic = file => {
    const fileType = ['jpg', 'jpe', 'jpeg', 'png', 'gif'];
    let isJpgOrPng = false;

    if (file.type && file.type != '') {
      fileType.some(s => {
        isJpgOrPng = file.type === getFileType(s);
        return isJpgOrPng;
      });
    } else {
      const name = file.name.split('.');
      const len = name.length;
      if (name && len > 0 && name[len - 1] && fileType.findIndex(f => f === name[len - 1]) > -1) {
        isJpgOrPng = true;
      }
    }
    return isJpgOrPng;
  };

  /** 预览图片 */
  const handlePreview = async file => {
    if (handleCheckIsPic(file)) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      setPreviewImage(file.url || file.preview);
      setPreviewVisible(true);
    } else {
      window.open(file.url);
    }
  };

  const handleGetValueFromEvent = e => {
    if (e && e.file && e.file.status === 'done') {
      // const id = /"id":"\d*"/.exec(e.file.response);
      // if (id && id.length > 0) {
      //     const i = /\d+/.exec(id[0]);
      //     if (i && i.length > 0) {
      //         return i[0];
      //     }
      // }
      // if (e.file.response.data && e.file.response.data.src) {
      //     return e.file.response.data.id;
      // }
      return fileList.map(i => i.uid);
    }
    if (e && e.file && e.file.status === 'removed') {
      return e && e.fileList.map(i => i.uid);
    }
    return null;
  };

  const handleChange = info => {
    if (info.file.status !== 'uploading') {
      // console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name}上传成功！`);
    } else if (info.file.status === 'error') {
      if (info.file.error.status === 401) {
        message.error(`暂无上传权限！`);
      } else {
        message.error(`${info.file.name}上传失败！`);
      }
    }

    /** 控制上传数量为1个 */
    let fileList = [...info.fileList];
    // 1. Limit the number of uploaded files
    // Only to show two recent uploaded files, and old ones will be replaced by the new
    fileList = fileList.slice(0 - uploadCount);
    // 2. Read from response and show file link
    fileList = fileList.map(f => {
      if (f.status === 'done') {
        // const reg = new RegExp('(http|https)://(\\S+?).' + file.name.split('.')[1] + '', 'g');
        // const path = reg.exec(file.response);
        // if (path && path.length > 0) {
        //     file.url = path[0];
        // }
        if (f.response && f.response.data && f.response.data.src) {
          f.url = f.response.data.src;
        }
        if (f.response && f.response.data && f.response.data.id) {
          f.uid = f.response.data.id;
        }
      }
      return f;
    });
    setFileList(fileList);
  };

  const uploadProps = {
    name: 'file',
    listType: 'picture',
    action: uploadUrl,
    // headers: {
    //   authorization: localStorage.getItem('ax-auth-token'),
    // },
    data: extraData,
    showUploadList: { showDownloadIcon: false },
    className: 'upload-list-inline',
    onPreview: handlePreview,
    onChange: handleChange,
  };

  switch (props.wholerow) {
    case 'two':
      formItemLayout = { ...inlineFormItemLayoutAllRowTwo };
      break;
    case 'three':
      formItemLayout = { ...inlineFormItemLayoutAllRowThree };
      break;
    default:
      formItemLayout = formItemLayoutFromProps
        ? formItemLayoutFromProps
        : { ...inlineFormItemLayout };
      break;
  }

  const uploadButton = (
    <>
      {/* <Icon type='plus' />
            <div className="ant-upload-text">可上传{uploadCount}个文件</div> */}
      <Button disabled={fileList.length >= uploadCount}>
        <Icon type="upload" /> 可上传{uploadCount}个文件
      </Button>
    </>
  );

  return props.hidden ? null : (
    <FormItem {...formItemLayout} label={props.label}>
      {props.form.getFieldDecorator(props.field, {
        initialValue: props.value && props.value.map(i => i.uid),
        getValueFromEvent: handleGetValueFromEvent,
        rules: [
          {
            label: props.label,
            required: props.required,
            message: props.message,
            validator: props.validator ? props.validator : AxValidator,
          },
        ],
      })(
        <Upload {...uploadProps} fileList={fileList}>
          {uploadButton}
        </Upload>,
      )}
      <AxModalShowPicture visible={previewVisible} handleCancel={handleCancel} src={previewImage} />
    </FormItem>
  );
}

/**
 * 选择图片（只选择，不上传）
 * @param {*} props
 */
export function AxUploadSelectPicture(props) {
  const [fileList, setFileList] = useState([]);
  const [imageUrl, setImageUrl] = useState(null);
  let formItemLayout = {};
  const { formItemLayoutFromProps = null, ...rest } = props;
  switch (props.wholerow) {
    case 'two':
      formItemLayout = { ...inlineFormItemLayoutAllRowTwo };
      break;
    case 'three':
      formItemLayout = { ...inlineFormItemLayoutAllRowThree };
      break;
    default:
      formItemLayout = formItemLayoutFromProps
        ? formItemLayoutFromProps
        : { ...inlineFormItemLayout };
      break;
  }
  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };

  const handleGetValueFromEvent = e => {
    getBase64(e.file, res => setImageUrl(res));
    return e.file;
  };

  /** 拦截文件上传 */
  const handleBeforeUpload = file => {
    setFileList([file]);
    return false;
  };

  const uploadButton = (
    <div>
      <Icon type="plus" />
      <div className="ant-upload-text">可上传{uploadCount}个文件</div>
    </div>
  );

  return props.hidden ? null : (
    <FormItem {...formItemLayout} label={props.label}>
      {props.form.getFieldDecorator(props.field, {
        // initialValue: props.value,
        getValueFromEvent: handleGetValueFromEvent,
        rules: [
          {
            label: props.label,
            required: props.required,
            message: props.message,
            validator: props.validator ? props.validator : AxValidator,
          },
        ],
      })(
        <Upload
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={false}
          beforeUpload={handleBeforeUpload}
          fileList={fileList}
        >
          {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
        </Upload>,
      )}
    </FormItem>
  );
}

/**
 * 图片展示弹框
 * @param {*} props
 */
export function AxModalShowPicture(props) {
  const { visible, handleCancel, src } = props;
  const [width, setWidth] = useState();

  useEffect(() => {
    getImageInfo(src, ({ width }) => {
      setWidth(width);
    });
  }, [src]);

  return (
    <Modal visible={visible} footer={null} onCancel={handleCancel} width={width}>
      <img alt="example" style={{ width: '100%' }} src={src} />
    </Modal>
  );
}

/** 获取图片信息 */
function getImageInfo(url, callback) {
  var img = new Image();
  img.src = url;
  if (img.complete) {
    // 如果图片被缓存，则直接返回缓存数据
    callback({ width: img.width, height: img.height });
  } else {
    img.onload = function() {
      callback({ width: img.width, height: img.height });
    };
  }
}
